<template>
  <div class="js-box flex-row-stretch-between-wrap">
    <!-- jsDemo1 -->
    <div class="js1 jsDiv">
      <div class="js1-title p-title flex-row-stretch-between">
        <p class="title">随机颜色</p>
        <p class="title" v-isShow="'js1'">隐藏</p>
        <p class="lookCode" @click="lookCode('js1')">
          查看代码
        </p>
      </div>
      <div class="leftOrright">
        <div class="js-main js1-main flex-row">
          <div class="demo" ref="demo">
            <div class="js1-main-button">
              <el-button type="primary" @click="randomColor">随机颜色1</el-button>
              <el-button type="primary" @click="randomColor2">随机颜色2</el-button>
              <el-button type="primary" @click="end">停止</el-button>
            </div>
            <div ref="randomColor" class="randomColor randomDiv">随机颜色1</div>
            <div ref="randomColor2" class="randomColor2 randomDiv">随机颜色2</div>
          </div>
          <div class="depict">
            <p class="depict-title">使用Math api</p>
            <ul>
              <li>1，此demo使用俩种方法实现</li>
              <li>2，第一个案例使用传统的'Math.random'生成R,G,B的三位随机数组成</li>
              <li>3，第二个案例为生成一个随机数，并且调用toString方法，转为16进制，并且使用substring方法截取2到8位</li>
            </ul>
          </div>
        </div>
        <prism-editor
          class="my-editor height-300"
          v-model="demo1"
          aria-disabled
          :highlight="highlighter"
          :line-numbers="lineNumbers"
          :readonly="readonlyType"
        />
      </div>
    </div>

    <!-- jsdemo2 -->
    <div class="js2 jsDiv">
      <div class="js2-title p-title flex-row-stretch-between">
        <p class="title">电池信息</p>
        <p class="title" v-isShow="'js2'">隐藏</p>
        <p class="lookCode" @click="lookCode('js2')">
          查看代码
        </p>
      </div>
      <div class="leftOrright">
        <div class="js-main js2-main flex-row">
          <div class="demo" ref="demo">
            <div class="js2-main-button">
              <el-button type="primary" @click="Lockbattery">查看电池信息</el-button>
            </div>
            <div class="batteryMain">
              <p>当前电量：<span>{{level}}</span></p>
              <p>电池剩余可用时间：<span>{{dischargingTime}}</span></p>
              <p>充满需要多久：<span>{{chargingTime}}</span></p>
              <p>是否在充电：<span>{{charging | isBooler}}</span></p>
            </div>
          </div>
          <div class="depict">
            <p class="depict-title">使用web Battery Status API</p>
            <ul>
              <li>1：Battery API 向 window.navigator 扩展了一个 navigator.getBattery 方法。</li>
              <li>2：其返回了一个 battery promise, 完成后传递一个 BatteryManager 对象，并提供了一些新的可以操作电池状态的事件</li>
              <li>3：charging: false: 是否在充电</li>
              <li>4：chargingTime: 0: 充满需要多久</li>
              <li>5：dischargingTime: '': 电池剩余可用时间</li>
              <li>6：level: 0: 剩余电量，最大电量为1</li>
            </ul>
          </div>
        </div>
        <prism-editor
          class="my-editor height-300"
          v-model="demo2"
          aria-disabled
          :highlight="highlighter"
          :line-numbers="lineNumbers"
          :readonly="readonlyType"
        />
      </div>
    </div>
  </div>
</template>

<script>
/* 代码编辑 */
import { PrismEditor } from "vue-prism-editor";
import "vue-prism-editor/dist/prismeditor.min.css"; // import the styles somewhere

// import highlighting library (you can use any library you want just return html string)
import { highlight, languages } from "prismjs/components/prism-core";
import "prismjs/components/prism-clike";
import "prismjs/components/prism-javascript";
import "prismjs/themes/prism-tomorrow.css"; // import syntax highlighting styles

import { demo1, demo2 } from './code/demo1';

export default {
  name: 'jsDemo',
  directives:{
    isShow:{
      bind(el, value){
        const {value: demoName} = value
        el.classList.add('titleBefore');
        el.addEventListener('click', function(e){
          let demo = document.getElementsByClassName(demoName)[0]
          // console.log(demo.classList)
          demo.classList.add('isDisplayNone');
        })
      },
    }
  },
  data(){
    return{
      isShow: null,
      // 代码模板
      demo1,
      demo2,
      // 代码提示
      lineNumbers: true, // true 显示行号   false 不显示行号
      readonlyType: false, //true不可编辑   false 可编辑
      // js1的data
      timerId1: null,
      timerId2: null,
      // js2的data
      charging: false,      // 是否在充电
      chargingTime: 0,      // 充满需要多久
      dischargingTime: '',  // 电池剩余可用时间
      level: 0,             // 剩余电量，最大电量为1

      isrotate: false,  //是否可操作
      rotateDivY: 0,
      rotateDivX: 0,
    }
  },
  components:{
    PrismEditor
  },
  mounted(){
    // this.addEvent()
    this.Lockbattery()
  },

  methods:{
    highlighter(code) {
      return highlight(code, languages.js); //returns html
    },
    /* js1 */
    end(){
      clearTimeout(this.timerId1);
      clearTimeout(this.timerId2);
    },
    randomNumber(){
      return Math.floor(Math.random() * 256)
    },
    randomColor(){
      let r = this.randomNumber(),
          g = this.randomNumber(),
          b = this.randomNumber();
      this.timerId1 = setTimeout(()=>{
        this.$refs.randomColor.style.background = `rgb(${r},${g},${b})`
        this.randomColor()
      },0)
    },
    randomColor2(){
      let rgb = ('#'+Math.random().toString(16).substring(2, 8))
      this.timerId2 = setTimeout(()=>{
        this.$refs.randomColor2.style.background = rgb
        this.randomColor2()
      },0)
    },

    /* js2 */
    Lockbattery(){
      navigator.getBattery().then((battery)=>{
        console.log(battery)
        this.charging = battery.charging
        // 计算时长
        // this.chargingTime = battery.chargingTime
        if(battery.chargingTime == Infinity){
          this.chargingTime = '暂无数据'
        }else{
          this.chargingTime = '暂无数据'
        }
        
        if(battery.dischargingTime == Infinity){
          this.dischargingTime = '正在充电'
        }else{
          this.dischargingTime = `${(battery.dischargingTime/60).toFixed(2)}分钟`
        }

        this.level = `${battery.level*100}%`
        // console.log(battery)
        battery.addEventListener("levelchange", function () {
          // 电量改变时触发该监听函数
          console.log(battery)
        });

        battery.addEventListener("chargingchange", function () {
          // 充电状态改变时触发该监听函数
        }, false);

        battery.addEventListener("chargingtimechange", function () {
          // 充满还需时间改变时触发该监听函数
          console.log(battery)
        }, false);

        battery.addEventListener("dischargingtimechange", function () {
          // 电池剩余可用时间改变时触发该监听函数
          console.log(battery)
        }, false);
      })
    },

    /* 查看代码 */
    lookCode(El){
      let el = document.getElementsByClassName(El)[0].getElementsByClassName('leftOrright')[0];
      let isClassStyle = el.classList.contains('translateLeft');
      if(!isClassStyle){
        el.classList.add('translateLeft');
      }else{
        el.classList.remove('translateLeft');
      }
    },
    /* 隐藏 */
    ishiddle(){
      console.log(this)
    }

    // addEvent(){
    //   let nodeDiv = this.$refs.randomColor
    //   let nodedemo = this.$refs.demo
    //   let demo1img = this.$refs.demo1img
    //   // nodeDiv.addEventListener('mousedown', this.moveclick)
    //   // nodeDiv.addEventListener('mousemove', this.movemousemove)
    //   // nodeDiv.addEventListener('mouseup', this.movemouseup)
    //   // nodeDiv.addEventListener('mouseleave', this.movemouseup)
    //   nodedemo.addEventListener('mousemove', this.movemousemove)
    // },
    // moveclick(e){
    //   this.isrotate = true
    // },
    // movemousemove(e){
    //   let demo1img = this.$refs.demo1img
    //   let rect = demo1img.getBoundingClientRect()
    //   let center = {
    //     x: rect.left + (rect.right - rect.left)/2,
    //     y: rect.top + (rect.bottom - rect.top)/2
    //   }
    //   let deg = Math.atan2(center.y - e.pageY, center.x - e.pageX) * (180 / Math.PI);
    // },
    // movemouseup(e){
    //   this.isrotate = false
    // },
    // fn(e){
    //   // console.log(e)
    //   // const {clientX, layerX, movementX, offsetX, pageX, screenX, tiltX, x } = e
    //   // console.log({clientX, layerX, movementX, offsetX, pageX, screenX, tiltX, x})
    //   // this.rotateDivY += movementX
    //   // this.$refs.randomColor.style.transform = `rotateY(${this.rotateDivY}deg)`
    //   // transform: rotateX(45deg);
    //   // const {clientX, clientY, layerX, layerYoffsetX, offsetY, pageX, pageY, x, y } = e
    //   // console.log({clientX, clientY, layerX, layerYoffsetX, offsetY, pageX, pageY, x, y })
    // },

  }

}
</script>

<style scoped lang="scss">
@import '../css/css/scrollbar.scss';
@import './css/comm.scss';
@import './css/index.scss';
@import './css/editor.scss';

.a{
  position: absolute;
  translate: -100%;
  display: none;
}
</style>